package design.prototype;

import java.util.HashMap;
import java.util.Map;

public class MyBatisⅡ {

    private Map<String, User> userCache = new HashMap<>();

    /**
     * 从数据库中查
     *
     * @param username
     * @return
     */
    public User getUser(String username) throws CloneNotSupportedException {
        User user = null;
        if (!userCache.containsKey(username)) {
            //缓存中没有，从数据库中查
            user = getUserFromDb(username);
            userCache.put(username, user);
        } else {
            //从缓存中直接获取，会导致脏缓存问题
            //拿到原型，但是不能直接给(本体)
            user = userCache.get(username);
            //从这个对象快速拿到克隆体
        }
        user = (User) user.clone();
        return user;
    }

    private User getUserFromDb(String username) {
        System.out.println("从数据库中查询:" + username);
        User user = new User();
        user.setName(username);
        user.setAge(20);
        return user;
    }
}
